package com.ostrich.ostrichgateway.config;



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ostrich.cloud.common.result.Result;
import com.ostrich.cloud.common.resultcode.CommonResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private JwtHelper jwtHelper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行登录请求
        String path = request.getURI().getPath();
        if(path.endsWith("Login") || path.endsWith("Register")||path.endsWith("changeStatus")){
            log.debug("放行登录请求:{}",path);
            return chain.filter(exchange);
        }

        //拦截其他请求
        String authToken = request.getHeaders().getFirst("auth_token");
        if(authToken==null||authToken.length()==0||authToken.trim().length()==0){
            return getVoidMono(exchange.getResponse());
        }
        //校验jwt
        try{
            Claims claims = jwtHelper.parseJWT(authToken);
            //提取jwt中的数据 放入请求头中 传给后续的服务
            Object userId = claims.get("operatorId");
            Object operatorName = claims.get("operatorName");
//            Object userId = claims.setId("userId");


//            if (path.contains("/api/ostrichManagerWeb/") && !"admin".equals(operatorName.toString())){
//                return getVoidMono((exchange.getResponse()));
//            }
//            if (path.contains("/api/ostrichBusinessWeb/") && !"businessman".equals(operatorName.toString())){
//                return getVoidMono((exchange.getResponse()));
//            }
//            if (path.contains("/api/ostrichUserWeb/") && !"customer".equals(operatorName.toString())){
//                return getVoidMono((exchange.getResponse()));
//            }
//            if (path.contains("/api/ostrichDistributionWeb/") && !"rider".equals(operatorName.toString())){
//                return getVoidMono((exchange.getResponse()));
//            }
            if(userId!=null){
                request.mutate().header("operatorId",userId.toString());
                request.mutate().header("operatorName",operatorName.toString());
            }

        }catch (JwtException e){
            return getVoidMono((exchange.getResponse()));
        }
        //提取jwt中的数据
        return chain.filter(exchange);
    }

    @Resource
    private ObjectMapper objectMapper;

    private Mono<Void> getVoidMono(ServerHttpResponse response) {
        Result result = Result.getInstance(CommonResultCode.NOT_AUTHORIZED);
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        try {
            String resultJson = objectMapper.writeValueAsString(result);
            DataBuffer dataBuffer = response.bufferFactory().wrap(resultJson.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON转换错误",e);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE-10;
    }
}
